package cn.echo.hrm.exception;

import cn.echo.hrm.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j//log4j标签
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        log.error("有错"+e.getErrorCode().getMessage());
        return AjaxResult.me().setSuccess(false)
                .setCode(e.getErrorCode().getCode())
                .setMessage(e.getErrorCode().getMessage());
    }

    //处理自定义异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(BusinessException e){
        e.printStackTrace();
        log.error("有错"+e.getMessage());
        return AjaxResult.me().setSuccess(false)
                .setCode(ErrorCode.CODE_500_SYSTEMERROR.getCode())
                .setMessage(ErrorCode.CODE_500_SYSTEMERROR.getMessage());
    }

    //处理jsr303异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidHandler(MethodArgumentNotValidException e){
        //获取多字段校验
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        //拼接错误信息
        StringBuffer stringBuffer = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            stringBuffer.append(fieldError.getDefaultMessage()+",");
            String s = stringBuffer.toString();
            s = s.substring(0, s.length() - 1);
        }

        log.error("有错"+e.getMessage());
        return AjaxResult.me().setSuccess(false).setMessage("系统异常");
    }
}
